<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row class="el-row-button">
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe border>
        <!-- 展开内容 -->
        <el-table-column type="expand">
          <template v-slot="scopes">
            <el-row :class="['bdbuttom', 'vcenter', it === 0 ? 'bgtop' : '']" v-for="(item, it) in scopes.row.children" closable :key="item.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="offTag(scopes.row, item.id)">
                  {{ it }} {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, it2) in item.children" :key="item2.id">
                  <!-- 通过for循环 嵌套渲染二级权限 -->
                  <el-col :span="7" :class="['vcenter', it2 === 0 ? '': 'bgtop' ]">
                    <el-tag closable type="success" @close="offTag(scopes.row, item2.id)">{{ it2 }}{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="17" :class="[ it2 === 0 ? '': 'bgtop' ]">
                    <!-- 循环第三级权限 -->
                    <el-tag closable @close="offTag(scopes.row, item3.id)" type="warning" v-for="( item3, it3 ) in item2.children" :key="item3.id">
                      {{ it3 }} {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 展开分配权限对话框 -->
    <el-dialog
      title="分配权限"
      v-model="setRightDialogVisible"
      width="50%"
      @close="setRightDiologClose">
      <!-- 树形控件 -->
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 分配权限的展开与关闭
      setRightDialogVisible: false,
      // 权限数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点ID值数组
      defKeys: [],
      // 当前即将分配权限的ID
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 所有角色列表数据
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
      // this.$message.success('获取角色列表成功！')
    },

    // 根据ID删除对应的权限
    async offTag(role, rightId) {
      console.log(role)
      console.log(role.children)
      const message = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      if (message !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      const { data: res } = await this.$axios.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      console.log(role.id + '-' + rightId)
      // this.getRolesList()
      // 调用该函数将重新渲染DOM
      role.children = res.data
      return this.$message.success('删除权限成功')
    },

    // 展示分配的对话框
    async setRightDialog(roles) {
      // 将获取的id保存起来
      this.roleId = roles.id
      // 递归获取所有的三级节点id
      this.getDefKeys(roles, this.defKeys)
      // 获取所有的权限
      const { data: res } = await this.$axios.get('rights/tree')

      if (res.meta.status !== 200) {
        this.$message.error('获取权限数据失败')
      }
      // 把获取到的权限数据保存到data中
      this.rightList = res.data
      // 展开分配权限的对话框
      this.setRightDialogVisible = true
    },

    // 通过递归的形式，获取角色下所有的三级权限ID，并保存到defKeys数组中
    getDefKeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // forEach() 方法用于调用数组的每个元素，并将元素传递给回调函数。
      // 此处是将node.children中的数值传递到getDefKeys回调函数中
      node.children.forEach(item => this.getDefKeys(item, arr))
    },

    setRightDiologClose() {
      this.defKeys = []
    },

    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        // 展开运算符，放入该数组中
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')

      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-row-button {
  margin-bottom: 15px;
}

.el-tag {
  margin: 7px;
}

.bgtop {
  border-top: 1px solid #eee;
}

.bdbuttom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
